<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');


/**
 * This class is for online shop order process - payment.
 * params order step
 * This is the children of controller.
 * PHP5 CMS Typolight
 * Copyright is 34n.sam@gmail.com
 */
 
 /**
 * Start page
 */
session_start();

class Validation_Server extends Controller
{
	/**
	 * This is class construct function.
	 * @params null
	 * @Return null
	 */
	public function __construct()
	{
		parent::__construct();
		header('Cache-Control: no-store, no-cache, must-revalidate');		
	}
	
	/** 
	 * Start page function
	 * @params null
	 * @Return null
	 */
	public function run()
	{
		if (!$_GET['method'])
			return;
		
		switch ($_GET['method'])
		{
			case 'Paypal':
				$status = $_POST['payment_status'];
				$insetId = $_POST['item_number'];
				$req = 'cmd=_notify-validate';
				foreach ($_POST as $key => $value) {
					$value = urlencode(stripslashes($value));
					$req .= "&$key=$value";
				}
				//建议在此将接受到的信息记录到日志文件中以确认是否收到 IPN 信息
				//将信息 POST 回给 PayPal 进行验证
				$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
				$header .= "Content-Type:application/x-www-form-urlencoded\r\n";
				$header .= "Content-Length:" . strlen($req) ."\r\n\r\n";
				//在 Sandbox 情况下，设置：
				$fp = fsockopen('ssl://www.sandbox.paypal.com',443,$errno,$errstr,30);
				
				//…
				//判断回复 POST 是否创建成功
				if (!$fp) 
				{
					//HTTP 错误
				}
				else 
				{
					//将回复 POST 信息写入 SOCKET 端口
					fputs ($fp, $header .$req);
					//开始接受 PayPal 对回复 POST 信息的认证信息
					while (!feof($fp)) 
					{
						$res = fgets ($fp, 1024);
						//已经通过认证
						if (strcmp ($res, "VERIFIED") == 0) 
						{
							//检查付款状态
							//检查 txn_id 是否已经处理过
							//检查 receiver_email 是否是您的 PayPal 账户中的 EMAIL 地址
							//检查付款金额和货币单位是否正确
							//处理这次付款，包括写数据库
							if ($status == "Completed" || $status == 'Processed')
								$succ="Y";
							else
								$succ="N";
							
							switch ($succ){
								//成功支付
								case "Y":
									$this->import("Database");
									$obj_order = $this->Database->prepare("SELECT * FROM `tl_orders` WHERE `id`=?")
																		->execute($insetId);
									if ($obj_order->numRows >= 1)
									{
										$obj_order = $this->Database->prepare("UPDATE `tl_orders` SET `odr_status`='2' WHERE `id`=?")
																		->execute($insetId);
										$obj_order_history = $this->Database->prepare("UPDATE `tl_order_history` SET `id_order_state`='2' WHERE `id_order`=?")
																		->execute($insetId);
										$obj_send_email = new ValidationPaypal();
										$obj_send_email->send_email($insetId);
									}				
									break;
									//支付失败
								case "N":									
									break;
							}
						}
						else if (strcmp ($res, "INVALID") == 0) 
						{
							//未通过认证，有可能是编码错误或非法的 POST 信息
						}
					}
					fclose ($fp);
				}
				break;
			case 'Alipay':
				#键名与pay_setting中设置的一致
				$mer_id = '2088202305942331';
				$mer_key = 'dq1mexi208a0l9f9irpizx49szj2rjld';         
				
				$insetId = $_POST['out_trade_no'];
				$this->import("Database");
				if($this->is_return_vaild($_POST,$mer_key))
				{					
					switch($_POST['trade_status'])
					{
						// ipn方式回来
						case 'WAIT_BUYER_PAY':
							break;
						case 'TRADE_FINISHED':
							$obj_order = $this->Database->prepare("SELECT * FROM `tl_orders` WHERE `id`=?")
																->execute($insetId);
							if ($obj_order->numRows >= 1)
							{
								$obj_order = $this->Database->prepare("UPDATE `tl_orders` SET `odr_status`='2' WHERE `id`=?")
																->execute($insetId);
								$obj_order_history = $this->Database->prepare("UPDATE `tl_order_history` SET `id_order_state`='2' WHERE `id_order`=?")
															->execute($insetId);
								$obj_send_email = new ValidationPaypal();
								$obj_send_email->send_email($insetId);
							}
							break;
						case 'TRADE_SUCCESS':
							$obj_order = $this->Database->prepare("SELECT * FROM `tl_orders` WHERE `id`=?")
																->execute($insetId);
							if ($obj_order->numRows >= 1)
							{
								$obj_order = $this->Database->prepare("UPDATE `tl_orders` SET `odr_status`='2' WHERE `id`=?")
																->execute($insetId);
								$obj_order_history = $this->Database->prepare("UPDATE `tl_order_history` SET `id_order_state`='2' WHERE `id_order`=?")
															->execute($insetId);
								$obj_send_email = new ValidationPaypal();
								$obj_send_email->send_email($insetId);
							}
							break;
						case 'WAIT_SELLER_SEND_GOODS':
							$obj_order = $this->Database->prepare("SELECT * FROM `tl_orders` WHERE `id`=?")
																->execute($insetId);
							if ($obj_order->numRows >= 1)
							{
								$obj_order = $this->Database->prepare("UPDATE `tl_orders` SET `odr_status`='2' WHERE `id`=?")
																->execute($insetId);
								$obj_order_history = $this->Database->prepare("UPDATE `tl_order_history` SET `id_order_state`='2' WHERE `id_order`=?")
															->execute($insetId);
								$obj_send_email = new ValidationPaypal();
								$obj_send_email->send_email($insetId);
							}
							break;
				   }

				}else{
					// 交易失败
				}
				break;
		}
	}

	/**
     * 检验返回数据合法性
     * @param mixed $form 包含签名数据的数组
     * @param mixed $key 签名用到的私钥
     * @access private
     * @return boolean
     */
    public function is_return_vaild($form,$key)
	{
        ksort($form);
        foreach($form as $k=>$v){
            if($k!='sign'&&$k!='sign_type'){
                $signstr .= "&$k=$v";
            }
        }

        $signstr = ltrim($signstr,"&");
        $signstr = $signstr.$key;   

        if($form['sign']==md5($signstr)){
            return true;
        }
         
        return false;
    }	
}

$validation = new Validation_Server();
$validation->run();
	
?>